﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;

namespace ZBJF.Warranty.BLL
{
    public partial class SellerInsuranceProductTagsService
    {
        public SellerInsuranceProductTags LoadByID(long id)
        {
            return LoadEntities(o => o.ID == id).FirstOrDefault();
        }

        public bool IsExist(long sellerInsuranceProductId, string tagName, long id = 0)
        {
            var expressionWhere = PredicateExtensions.True<SellerInsuranceProductTags>().And(o => o.TagName.Equals(tagName) && o.SellerInsuranceProductId == sellerInsuranceProductId);
            if (id > 0)
                expressionWhere = expressionWhere.And(o => o.ID != id);
            return LoadEntities(expressionWhere).Any();
        }

        public bool AddTags(long sellerInsuranceProductId, List<string> tagNames)
        {
            var result = true;
            try
            {
                if (sellerInsuranceProductId > 0 && tagNames != null && tagNames.Any())
                {
                    for (int i = 0; i < tagNames.Count; i++)
                    {
                        var tagName = tagNames[i];
                        if (!string.IsNullOrEmpty(tagName))
                        {
                            if (!IsExist(sellerInsuranceProductId, tagName))
                            {
                                result = AddEntities(new SellerInsuranceProductTags()
                                {
                                    SellerInsuranceProductId = sellerInsuranceProductId,
                                    TagName = tagName
                                }).ID > 0;
                            }
                        }
                    }
                    var toBeDeleteRoleMappings = LoadEntities(o => o.SellerInsuranceProductId == sellerInsuranceProductId && !tagNames.Contains(o.TagName)).ToList();
                    toBeDeleteRoleMappings.ForEach(o => result = DeleteEntities(o));
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        public IQueryable<SellerInsuranceProductTags> LoadBySellerInsuranceProductId(long sellerInsuranceProductId)
        {
            return LoadEntities(o => o.SellerInsuranceProductId == sellerInsuranceProductId);
        }

    }
}
